package com.aruba.itemtouchhelperapplication;

import android.graphics.Canvas;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.aruba.itemtouchhelperapplication.itemtouchhelper.ItemTouchHelper;


public class ItemTouchHelperCallback extends ItemTouchHelper.Callback {
    private IMoveAndSwipeCallback iMoveAndSwipeCallback;

    public void setiMoveAndSwipeCallback(IMoveAndSwipeCallback iMoveAndSwipeCallback) {
        this.iMoveAndSwipeCallback = iMoveAndSwipeCallback;
    }

    /**
     * 设置拖拽和item滑动的可支持方向
     *
     * @param recyclerView
     * @param viewHolder
     * @return
     */
    @Override
    public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
        //支持上下拖拽
        final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        //item支持左滑
        final int swipeFlags = ItemTouchHelper.LEFT;

        return makeMovementFlags(dragFlags, swipeFlags);
    }

    /**
     * 拖拽结束后（手指抬起）会回调的方法
     *
     * @param recyclerView
     * @param viewHolder   手指拖拽的item
     * @param viewHolder1  移动到的item
     * @return
     */
    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder viewHolder1) {
        if (iMoveAndSwipeCallback != null) {
            iMoveAndSwipeCallback.onMove(viewHolder.getAdapterPosition(), viewHolder1.getAdapterPosition());
        }
        return true;
    }

    /**
     * 侧滑回调
     *
     * @param viewHolder
     * @param swipeDir   方向
     */
    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int swipeDir) {
        if (iMoveAndSwipeCallback != null) {
            iMoveAndSwipeCallback.onSwiped(viewHolder.getAdapterPosition());
        }
    }

    @Override
    public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        if (dY != 0 && dX == 0) {//因为我们只关注侧滑，而侧滑条件是dX！=0&&dY ==0，所以其他的情况调用ItemTouchUIUtilImpl的方法
            super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
        }

        if (iMoveAndSwipeCallback != null) {
            iMoveAndSwipeCallback.onChildDraw(viewHolder, dX, dY);
        }
    }

    @Override
    public View getItemFrontView(RecyclerView.ViewHolder mPreOpened) {
        if (iMoveAndSwipeCallback != null) {
            return iMoveAndSwipeCallback.getItemFrontView(mPreOpened);
        }
        return null;
    }
}
